package com.winchain.chainbill.bill.biz.discount.cmd;

import com.shell.bee.contract.ContService;
import com.shell.bee.contract.po.ContBas;
import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICommand;
import com.shell.framework.utils.CommonDataUtil;
import com.winchain.chainbill.basic.cus.po.CusRec;
import com.winchain.chainbill.basic.cus.service.CusRecService;
import com.winchain.chainbill.bill.base.po.CbDct;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.biz.Bill;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillDctSerFeeDebitBatchSignCmd implements ICommand<Bill<CbDct>> {
	@Autowired
	private ContService contService;
	@Autowired
	private CusRecService cusRecService;

	public boolean execute(CommandContext<Bill<CbDct>> context) throws Exception {
		CbRec bill = ((Bill) context.getSource()).getRec();

		String zySign = context.getStringValue("zySign");
		if ("1".equals(zySign)) {
			CusRec artisan = this.cusRecService.getArtisan(null);
			signLocal(artisan.getCusId(), bill.getBillId());
		}
		String custId = CommonDataUtil.getCurEntId();
		signLocal(custId, bill.getBillId());

		return false;
	}

	private void signLocal(String custId, String billId) {
		ContBas cont = this.contService.getLatestCont(custId, billId, "18", null);
		if (cont != null) {
			boolean finished = false;
			if (!custId.equals(cont.getSponsor())) {
				if ("18".equals(cont.getBizType())) {
					if (custId.equals(cont.getWitness())) {
						finished = true;
					}
				} else if (custId.equals(cont.getAcceptor())) {
					finished = true;
				}
			}
			if (finished) {
				cont.setContProgress("1");
			}
			this.contService.sign(cont, custId);
		}
	}
}
